package com.ctjsoft.datacollection.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctjsoft.datacollection.core.dto.RepositoryDTO;
import com.ctjsoft.datacollection.core.povo.Result;
import com.ctjsoft.datacollection.core.repository.RepositoryUtil;
import com.ctjsoft.datacollection.entity.*;
import com.ctjsoft.datacollection.mapper.DiCategoryMapper;
import com.ctjsoft.datacollection.mapper.DiScriptMapper;
import com.ctjsoft.datacollection.mapper.KDatabaseTypeMapper;
import com.ctjsoft.datacollection.mapper.KRepositoryMapper;
import com.ctjsoft.datacollection.service.DiCategoryService;
import com.ctjsoft.datacollection.service.DiScriptService;
import com.ctjsoft.datacollection.util.BeanUtil;
import com.ctjsoft.datacollection.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.AbstractRepository;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class DiCategoryServiceImpl extends ServiceImpl<DiCategoryMapper, DiCategory> implements DiCategoryService {
    @Autowired
    DiCategoryMapper diCategoryMapper;
    @Autowired
    DiScriptMapper diScriptMapper;
    @Autowired
    KRepositoryMapper kRepositoryMapper;
    @Value("${spoon.url}")
    private String REPOSITORY_URL;
    @Override
    public void delete(String id) {
        try {
            DiCategory diCategory = diCategoryMapper.selectById(id);
            // isDefault为1不能删除
            String repId = diCategory.getRepId();
            if (!DiCanstant.IS_DEFAULT.equals(diCategory.getIsDefault())) {
                KRepository kRepository = kRepositoryMapper.selectById(repId);
                if (kRepository !=null) {
                    // 连接资源库
                    AbstractRepository repository = RepositoryUtil.connection(kRepository);
                    if (!repository.isConnected()) {
                        repository.connect(kRepository.getRepUsername(), kRepository.getRepPassword());
                    }
                    RepositoryDirectoryInterface d = repository.findDirectory(diCategory.getPath());
                    // 删除子目录
                    List<DiCategory> all = diCategoryMapper.selectByRepId(repId);
                    List<String> categorys = new ArrayList<>();
                    // 找到目录下所有子目录Id
                    DiScriptServiceImpl.getChildCategoryId(diCategory, all, categorys);
                    categorys.add(diCategory.getCategoryId());
                    // 删除存在数据库的目录
                    diCategoryMapper.deleteByCategoryIdInAndRepId(categorys, repId);
                    if (Objects.nonNull(d)) {
                        repository.deleteRepositoryDirectory(d);
                    }
                    // 删除对应目录下的转换和job
                    diScriptMapper.deleteByCategoryIdInAndRepId(categorys, repId);
                }
            }
        } catch (KettleException e) {
            e.printStackTrace();
        }
    }
    public void update(DiCategory diCategory) {
        try {
            String repId = diCategory.getRepId();
            KRepository kRepository = kRepositoryMapper.selectById(repId);
            DiCategory byId = diCategoryMapper.selectById(diCategory.getId());
            if (kRepository!=null) {
                AbstractRepository repository = RepositoryUtil.connection(kRepository);
                if (!repository.isConnected()) {
                    repository.connect(kRepository.getRepUsername(), kRepository.getRepPassword());
                }
                RepositoryDirectoryInterface d = repository.findDirectory(byId.getPath());
                RepositoryDirectoryInterface directoryInterface = null;
                if (StringUtils.isEmpty(byId.getCategoryPid())) {
                    directoryInterface = repository.findDirectory(DiCanstant.FILE_SEPARATOR);
                    byId.setPath( DiCanstant.FILE_SEPARATOR + diCategory.getName());
                } else {
                    DiCategory pCatrgory = diCategoryMapper.findByCategoryIdAndRepId(byId.getCategoryPid(), byId.getRepId());
                    directoryInterface = repository.findDirectory(pCatrgory.getPath());
                    byId.setPath(pCatrgory.getPath() + DiCanstant.FILE_SEPARATOR + diCategory.getName());
                }
                repository.renameRepositoryDirectory(d.getObjectId(), directoryInterface, diCategory.getName());
                byId.setName(diCategory.getName());
                diCategoryMapper.updateById(byId);
            }
        } catch (KettleException e) {
            e.printStackTrace();
        }
    }
    public List<DiCategory> findDiCateryByRep(String repId) {
        List<DiCategory> all = diCategoryMapper.findByRepIdOrderByCode(repId);
        return all;
    }
    public DiRespository findRepositoryById(String id) {
        KRepository kRepository = kRepositoryMapper.selectById(id);
        DiRespository repDto = null;
        if (kRepository!=null) {
            repDto = BeanUtil.copyProperties(kRepository, DiRespository.class);
        }
        repDto.setUrl(REPOSITORY_URL);
        return repDto;
    }
    public Result add(DiCategory dca) {
        try {
            String repId = dca.getRepId();
            DiCategory cr = diCategoryMapper.selectById(dca.getId());
            // 判断该目录名称是否存在
            List<DiCategory> categoryList = diCategoryMapper.findByCategoryPidAndRepId(cr.getCategoryId(), repId);
            List<String> collect = categoryList.stream().map(DiCategory::getName).collect(Collectors.toList());
            if (collect.contains(dca.getName())) {
                return Result.error("500", "该目录已存在");
            }
            KRepository kRepository=kRepositoryMapper.selectById(repId);
            if (kRepository!=null) {
                // 连接资源库
                AbstractRepository repository = RepositoryUtil.connection(kRepository);
                if (!repository.isConnected()) {
                    repository.connect(kRepository.getRepUsername(), kRepository.getRepPassword());
                }
                RepositoryDirectoryInterface directory = null;
                directory = repository.findDirectory(cr.getPath());
                dca.setPath(cr.getPath() + DiCanstant.FILE_SEPARATOR + dca.getName());
                dca.setCategoryPid(cr.getCategoryId());
                if (Objects.nonNull(directory)) {
                    repository.createRepositoryDirectory(directory, dca.getName());
                }
                dca.setCategoryId(StringUtil.uuid());
                dca.setId(StringUtil.uuid());
                dca.setIsDefault("0");
                // 新增编码按照3-3-3的形式
                Optional<DiCategory> max = categoryList.stream().max(Comparator.comparing(DiCategory::getCode));
                String code = max.get().getCode();
                int length = code.length();
                String s = code.substring(length - 3).replaceAll("^(0+)", "");
                int i = Integer.parseInt(s) + 1;
                String format = String.format("%03d", i);
                System.out.println(code.substring(0, length - 3));
                System.out.println(format);
                dca.setCode(code.substring(0, length - 3) + format);
                diCategoryMapper.insert(dca);
            }
        } catch (KettleException e) {
            e.printStackTrace();
            return Result.error("500",e.getMessage());
        }
        return Result.ok();
    }
}
